//
//  ForgotPasswordViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/12/28.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "ForgotPasswordViewController.h"
#import "SystemResetPwdViewController.h"
#import "HttpRequest.h"
#import "JSONKit.h"
//#import "phoneViewController.h"
#import "HAODEsingleton.h"
@interface ForgotPasswordViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate >

@end

@implementation ForgotPasswordViewController

{
    UITextField* UserNameTextField;
    UITextField* PasswordTextField;
    UITextField* VerificationCode;
    UIButton* ToObtain;
    UIView*view1;
    HAODEsingleton*commdity;
    UIView*myToolBar;
}
@synthesize alt = alt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
       UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    commdity=[HAODEsingleton shared];
    self.title = @"找回密码";
    
    
    // 手势
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [self.view addGestureRecognizer:singleFingerOne];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    
    view1 = [[UIView alloc]initWithFrame:CGRectMake(0,64+37.5, ScreenWidth, 88)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
//    UILabel *line0 = [[UILabel alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, 0.5)];
//    line0.backgroundColor =labelColor;
//    [view1 addSubview:line0];
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(15.0f,88/2, ScreenWidth-30, 0.5)];
    line1.backgroundColor = labelColor;
    [view1 addSubview:line1];
    UILabel *line3 = [[UILabel alloc]initWithFrame:CGRectMake(15,88, ScreenWidth-30, 0.5)];
    line3.backgroundColor = labelColor;
    [view1 addSubview:line3];
    
    UserNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-35, 44)];
    [UserNameTextField setBorderStyle:UITextBorderStyleNone]; //外框类型
    UserNameTextField.keyboardType = UIKeyboardTypeDecimalPad;
    UserNameTextField.placeholder = @"请输入手机号码"; //默认显示的字
    UserNameTextField.font = [UIFont systemFontOfSize: 15.0];
    UserNameTextField.returnKeyType = UIReturnKeyDone;
    UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    UserNameTextField.delegate = self;
    
    [UserNameTextField addTarget:self action:@selector(userNumberLimitTextLength:) forControlEvents:UIControlEventEditingChanged];
    [view1 addSubview:UserNameTextField];
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    NSString* UserName = [userDefault objectForKey:@"UserNameTextField"];
    UserNameTextField.text=UserName;

    
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:daxiao];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];    UserNameTextField.inputAccessoryView = myToolBar;
    
    
    VerificationCode = [[UITextField alloc] initWithFrame:CGRectMake(15, 44, 130, 44)];
    [VerificationCode setBorderStyle:UITextBorderStyleNone]; //外框类型
    VerificationCode.placeholder = @"输入手机验证码"; //默认显示的字
    VerificationCode.secureTextEntry = YES; //密码
    VerificationCode.font = [UIFont systemFontOfSize: 15.0];
    VerificationCode.keyboardType = UIKeyboardTypeDecimalPad;
    VerificationCode.autocorrectionType = UITextAutocorrectionTypeNo;
    VerificationCode.autocapitalizationType = UITextAutocapitalizationTypeNone;
    VerificationCode.returnKeyType = UIReturnKeyDone;
    VerificationCode.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    VerificationCode.delegate = self;
    [view1 addSubview:VerificationCode];
    VerificationCode.inputAccessoryView = myToolBar;
    
    ToObtain = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth*930/1240,55,  ScreenWidth*245/1240,25)];
    [ToObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
    ToObtain.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [ToObtain.layer setCornerRadius:3.0]; //设置矩圆角半径
    [ToObtain.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){224/255.0, 224/255.0, 224/255.0, 1.0});
    [ToObtain.layer setBorderColor:tureBTncolorref];//边框颜色
    [ToObtain setTitleColor:hongsecolor forState:UIControlStateNormal];    ToObtain .titleLabel.textAlignment=NSTextAlignmentRight;
    [ToObtain addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:ToObtain];
    
    
    
    UIButton* login = [[UIButton alloc] initWithFrame:CGRectMake(10,  200+64, ScreenWidth-20, anniuHeigth)];
    [login setTitle:@"下一步" forState:UIControlStateNormal];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    login.backgroundColor=luseColor;
    [login.layer setCornerRadius:2.0]; //设置矩圆角半径
    [login.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace1 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref1 = CGColorCreate(tureBTnSpace1,(CGFloat[]){204.0/255.0,204.0/255.0, 204.0/255.0, 1.0 });
    [login.layer setBorderColor:tureBTncolorref1];//边框颜色
    
    [login addTarget:self action:@selector(regist:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:login];
    
    
    
}

//账号长度限制
- (void)userNumberLimitTextLength:(UITextField*)textField
{
    if ([textField.text length] > 11)
    {
        textField.text = [textField.text substringToIndex:11];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    
    
    return YES;
}

-(void)startTime{
    
    if ([UserNameTextField.text length] != 11)
    {
        [self showAlertMessage:@"手机输入有误"];
    }
    else
    {
        
        __block int timeout=60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    
                    
                    
                    
                    [ToObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
                    ToObtain.userInteractionEnabled = YES;
                });
            }else{
                //            int minutes = timeout / 60;
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    //                NSLog(@"____%@",strTime);
                    if (strTime.intValue==59) {
                        NSLog(@"____%@",strTime);
                        
                        
                        
                        NSMutableDictionary *params = [NSMutableDictionary new];
                        [params setValue:UserNameTextField.text forKey:@"mobile"];
                        [params setValue:@"F" forKey:@"msgType"];
                        [HttpRequest requestData:@"System/SendMsg" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                            if (isSuccess) {
                                NSLog(@"====%@",severDataDict.dataDict);
                                
                                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                    [Global hideProgressHUDInternal:self.view];
                                    
                        
                                NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];

                                                                     
                                    [self showAlertMessage:ResultString];
                                    
                                    
                                }else{
                                    
                                    
                                    [Global hideProgressHUDInternal:self.view];
                                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                    // [Global showTextHud:requestResultStr view:self.view];
                                    [Global showTextHudSub:requestResultStr view:self.view];
                                    
                                    
                                    
                                    
                                }
                                
                            }
                            else
                            {
                                [Global hideProgressHUDInternal:self.view];
                                
                                [Global showTextHudSub:@"连接失败" view:self.view];
                                
                                
                                
                            }
                            
                        }];
                    }
                    
                    
                    
                    
                    
                    
                    
                    [ToObtain setTitle:[NSString stringWithFormat:@"%@秒重获",strTime] forState:UIControlStateNormal];
                    ToObtain.userInteractionEnabled = NO;
                    
                });
                timeout--;
                
            }
        });
        dispatch_resume(_timer);
        
    }
    
}

-(void)regist:(UIButton*)sender{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"Token"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"Token"];
    [params setValue:UserNameTextField.text forKey:@"ucode"];
    
    [params setValue:VerificationCode.text forKey:@"mcode"];
 
    [HttpRequest requestData:@"System/ForgetPwd" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];

//        NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];
        
                commdity.ucode=UserNameTextField.text;
             
                commdity.vcode=[severDataDict.dataDict objectForKey:@"vcode"];
            
            SystemResetPwdViewController *generateVC=[[SystemResetPwdViewController alloc] init];
            [self.navigationController pushViewController:generateVC animated:YES];
            
            
            
        
            }else{
                
                
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                // [Global showTextHud:requestResultStr view:self.view];
                [Global showTextHudSub:requestResultStr view:self.view];
                
                
                
                
        }
        
    }
     else
     {
         [Global hideProgressHUDInternal:self.view];
         
         [Global showTextHudSub:@"连接失败" view:self.view];
         
         
         
     }
     
     }];

    
}


- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定哦 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:4.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)OnTapDone{
    
    [UserNameTextField resignFirstResponder];
    [VerificationCode resignFirstResponder];
    //    [VerificationCode resignFirstResponder];
    
    
    
    
}
//回收键盘
-(void)closeKeyBoad
{
    [UserNameTextField resignFirstResponder];
    [VerificationCode resignFirstResponder];
    //    [VerificationCode resignFirstResponder];
}


@end
